package cn.uncode.baas.server.vo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import cn.uncode.dal.criteria.Model;
import cn.uncode.dal.utils.JsonUtils;
import cn.uncode.baas.server.constant.Resource;

public class One2manyVo implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 487996655594334620L;
	
	private O2oVo many;
	private O2oVo join;
	private String desc;
	
	public static One2manyVo valueOf(String value){
		if(StringUtils.isNotBlank(value)){
			Map<?, ?> om = JsonUtils.fromJson(value, Map.class);
			return valueOf(om);
		}
		return null;
	}
	
	public static One2manyVo valueOf(Map<?,?> map){
		
		if(map != null){
			One2manyVo vo = new One2manyVo();
			if(map.containsKey(Resource.REST_TABLE_ONE_TO_MANY_MANY_KEY)){
				Map<?,?> my = (Map<?, ?>) map.get(Resource.REST_TABLE_ONE_TO_MANY_MANY_KEY);
				if(null != my){
					vo.setMany(O2oVo.valueOf(my));
				}
			}
			if(map.containsKey(Resource.REST_TABLE_ONE_TO_MANY_JOIN_KEY)){
				Map<?,?> join = (Map<?, ?>) map.get(Resource.REST_TABLE_ONE_TO_MANY_JOIN_KEY);
				if(null != join){
					vo.setJoin(O2oVo.valueOf(join));
				}
			}
			if(map.containsKey(Resource.REST_TABLE_ONE_TO_MANY_DESC_KEY)){
				String desc = String.valueOf(map.get(Resource.REST_TABLE_ONE_TO_MANY_DESC_KEY));
				if(StringUtils.isNotEmpty(desc)){
					vo.setDesc(desc);
				}
			}
			return vo;
		}
		return null;
	}
	
	public O2oVo getMany() {
		return many;
	}
	public void setMany(O2oVo many) {
		this.many = many;
	}
	public O2oVo getJoin() {
		return join;
	}
	public void setJoin(O2oVo join) {
		this.join = join;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}
	
	public boolean isMiddleTableReuse(){
		if(null == many || null == join){
			return false;
		}
		if(many.getTable().equals(join.getTable())){
			return true;
		}
		return false;
	}
	
	public Model getAddModel(int oneId, int manyId){
		Model model = new Model(join.getTable());
		Map<String, Object> content = new HashMap<String, Object>();
		if(isMiddleTableReuse()){
			if("id".equals(join.getField2())){
				model.setSinglePrimaryKey(manyId);
			}else{
				content.put(join.getField2(), manyId);
			}
			content.put(join.getField(), oneId);
		}else{
			content.put(join.getField2(), manyId);
			content.put(join.getField(), oneId);
		}
		model.addContent(content);
		return model;
	}
	
	public Model getDelModel(int manyId){
		Model model = new Model(join.getTable());
		Map<String, Object> content = new HashMap<String, Object>();
		if(isMiddleTableReuse()){
			if("id".equals(join.getField2())){
				model.setSinglePrimaryKey(manyId);
			}else{
				content.put(join.getField2(), manyId);
			}
			content.put(join.getField(), 0);
			model.addContent(content);
		}else{
			model.setSinglePrimaryKey(manyId);
		}
		return model;
	}
	
	

}
